#!/bin/bash

# Provide source directive to shellcheck.
# shellcheck source=meta-facebook/meta-greatlakes/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

HOST_ID=$1
SLOT_ID=$(( $1-1  << 2 ))

# Host Reboot
host-reboot()
{
    for reset_cmd in "${reset_seq[@]}"
    do
        response="$(busctl call "$SERVICE" "$OBJECT_PATH" "$INTERFACE" sendRequest yyyyay "$SLOT_ID" "$NETFN" "$LUN" "$CMD" "$DATA_LEN" 0x01 0x42 0x01 0 "$reset_cmd")"
        echo "$response"
        result=$(echo "$response" | cut -d" " -f "$IPMB_CMD_COMPLETE_CODE_INDEX")
        if [ "$result" -ne 0 ]
        then
            echo "Failed to send ipmb command"
            exit 1
        fi
        if [ "$reset_cmd" == "$POWER_BTN_LOW" ]
        then
            sleep "$1"
        fi
    done

    # Check host stattus after doing host power reset
    host_status=$(host-power-status $SLOT_ID)
    if [ "$host_status" == "$STATE_ON" ]
    then
        busctl set-property "$HOST_BUS_NAME""$HOST_ID" "$HOST_OBJ_PATH""$HOST_ID" "$HOST_INTF_NAME" "$HOST_PROPERTY_NAME" s "$HOST_ON"
        echo "Host power Reset"
        exit 0;
    else
        busctl set-property "$HOST_BUS_NAME""$HOST_ID" "$HOST_OBJ_PATH""$HOST_ID" "$HOST_INTF_NAME" "$HOST_PROPERTY_NAME" s "$HOST_OFF"
        echo "Host power off"
        exit 0;
    fi
}

# Check Host Response and Status
host_status=$(host-power-status $SLOT_ID)
if [ "$host_status" == "$STATE_ON" ]
then
    host-reboot 1
else
    echo "Host is Off"
    exit 1;
fi
